package com.jlastu.znb.presenter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

import androidx.annotation.NonNull;

import com.jlastu.znb.base.WeakRefHandler;
import com.jlastu.znb.contract.SchoolContract;
import com.jlastu.znb.entity.News;
import com.jlastu.znb.entity.NewsPhoto;

import java.util.ArrayList;
import java.util.List;

public class SchoolPresenter implements SchoolContract.ISchoolPresenter {

    private static final int WHAT_SHOW_CATEGORY_NEWS = 1;
    private SchoolContract.ISchoolView mSchoolView;
    private Context mContext;

    public SchoolPresenter(SchoolContract.ISchoolView schoolView, Context context) {
        mSchoolView = schoolView;
        mContext = context;
    }

    public void getNewsByCategory(String category) {
        List<News> list = new ArrayList<>();
        new Thread(new Runnable() {
            @SuppressLint("Range")
            @Override
            public void run() {
                // 此处异步进行数据查询
                Uri uri = Uri.parse("content://com.jlastu.znb.provider/news_by_category/" + category);
                Log.d("TAG", "run: " + category);
                Cursor cursor = mContext.getContentResolver().query(
                        uri, null, "category = ?", new String[]{category}, null);
                try {
                    if (cursor != null && cursor.moveToFirst()) {
                        do {
                            News news = new News();
                            int news_id = cursor.getInt(cursor.getColumnIndex("_id"));
                            news.setId(news_id);
                            news.setTitle(cursor.getString(cursor.getColumnIndex("title")));
                            news.setSubtitle(cursor.getString(cursor.getColumnIndex("subtitle")));
                            news.setDate(cursor.getString(cursor.getColumnIndex("date")));
                            Log.d("TAG", "run4: " + mContext);

                            Uri photoUri = Uri.parse("content://com.jlastu.znb.provider/newsphoto");
                            String photoSelection = "news_id = ?";
                            String[] photoSelectionArgs = new String[]{String.valueOf(news_id)};
                            Cursor photoCursor = mContext.getContentResolver().query(
                                    photoUri,
                                    null,
                                    photoSelection,
                                    photoSelectionArgs,
                                    null);
                            Log.d("TAG", "query: "+mContext);

                            if (photoCursor != null && photoCursor.moveToFirst()) {
                                do {
                                    NewsPhoto photo = new NewsPhoto();
                                    photo.setId(photoCursor.getInt(photoCursor.getColumnIndex("_id")));
                                    photo.setData(photoCursor.getBlob(photoCursor.getColumnIndex("image")));
                                    news.addPhoto(photo);
                                } while (photoCursor.moveToNext());
                            }
                            Log.d("", "news ====== " + news.toString());
                            list.add(news);
                        } while (cursor.moveToNext());
                    } else {
                        Log.d("TAG", "run: " + 123);
                    }

                } finally {
                    if (cursor != null) {
                        cursor.close();
                    }
                }
                // 子线程通过Handler发送消息，完成线程之间的通信。
                Message message = Message.obtain();
                message.obj = list;
                message.what = WHAT_SHOW_CATEGORY_NEWS;
                mHandler.sendMessage(message);
            }
        }).start();
    }

    Handler mHandler = new WeakRefHandler<>(Looper.getMainLooper(), this, new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            if (msg.what == WHAT_SHOW_CATEGORY_NEWS) {
                mSchoolView.showNewsByCategory((List<News>) msg.obj);
            }
            return false;
        }
    });

    private String[] getNewsIds(List<News> newsList) {
        String[] ids = new String[newsList.size()];
        for (int i = 0; i < newsList.size(); i++) {
            ids[i] = String.valueOf(newsList.get(i).getId());
        }
        return ids;
    }
}

